import os
import xlwt

""" 读取原始数据： eyeTrack_dict以字典的格式储存， eyeTrack_dict[顺序编号] = list([可视化区域, 持续时间]) """
def loadEyeTrackerData(file_path):
    print("begin reading eye tracker data of ", file_path)
    eyeTrack_dict = {}
    with open(file_path, "r", encoding="utf8", errors="ignore") as file:
        for i, line in enumerate(file.readlines()):
            split = line.strip("\n").split(",")
            if len(split) != 3:
                print("This %d line - %s - is in the wrong format"%(i, line.strip("\n")))
            else:
                category, duration = str(split[0]), int(split[-1])
                eyeTrack_dict[i] = list([category, duration])
    return eyeTrack_dict


def outputProbData(dir_path, file_name, data_dict):
    dir_path = str(dir_path)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    with open(dir_path + file_name, "w", encoding="utf8", errors="ignore") as file:
        for key in data_dict.keys():
            file.write(data_dict[key][0] + "," + str(data_dict[key][-1]))
            file.write("\n")



""" 两种数据构造方式：
 1. 将“注视”信息按照 时间/总长 的方式转变成概率数据；
 2. 将“注视转移”信息按照 注视A/注视B 的方式转变成概率数据。
 """

"""  1. 将“注视”信息按照 时间/总长 的方式转变成概率数据 """
def crateGazeProbData(raw_data):
    get_duration = lambda item: item[-1]
    total_duration = sum([get_duration(item) for item in list(raw_data.values())])
    Gaze_Prob_Data = {id: [raw_data[id][0], raw_data[id][-1]/total_duration] for id in raw_data.keys()}
    # print(Gaze_Prob_Data)
    return Gaze_Prob_Data

"""  2. 将“注视转移”信息按照 注视A/注视B 的方式转变成概率数据。 """
def crateGazeTrackProbData(raw_data):
    get_duration = lambda item: item[-1]
    total_duration = sum([get_duration(item) for item in list(raw_data.values())])
    key_list = sorted(list(raw_data.keys()))
    GazeTrack_Prob_Data = {key:["%s->%s"%(raw_data[key_list[i-1]][0], raw_data[key][0]), (raw_data[key_list[i-1]][1] + raw_data[key][1]) / (total_duration*2-raw_data[key_list[0]][1]-raw_data[key_list[-1]][1])] for i, key in enumerate(key_list) if i > 0}
    # print(GazeTrack_Prob_Data)
    return GazeTrack_Prob_Data


def crateXlsFile(dir_path, sheet_name_list):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    workbook = xlwt.Workbook()
    sheet_dict = {}
    for sheet_name in sheet_name_list:
        worksheet = workbook.add_sheet(sheet_name)
        sheet_dict[sheet_name] = worksheet
    return workbook, sheet_dict


def outputPatternToXlwt(worksheet , Pattern_Summary_Dict, user_list, sort_by):
    from miningFuntion import Classical_Sequential_Pattern
    worksheet.write(0, 0, "user_name")
    worksheet.write(0, 1, "pattern_name")
    worksheet.write(0, 2, "length")
    worksheet.write(0, 3, "support")
    worksheet.write(0, 4, "absolute rarity")
    worksheet.write(0, 5, "relative rarity")
    worksheet.write(0, 6, "typical")
    """ pattern_name, length, support """
    i = 0
    for user_id in user_list:
        pattern_name_list = []
        if sort_by == "support":
            PATTERN_LIST = sorted(Pattern_Summary_Dict[user_id].items(), key=lambda item: item[-1].support, reverse=True)
            pattern_name_list = list(dict(PATTERN_LIST[0:256]).keys())
        elif sort_by == "typical":
            PATTERN_LIST = sorted(Pattern_Summary_Dict[user_id].items(), key=lambda item: item[-1].AP, reverse=True)
            pattern_name_list = list(dict(PATTERN_LIST[0:10]).keys())

        """ 排序后的结果输出 """
        for j, key in enumerate(pattern_name_list):
            if (Pattern_Summary_Dict[user_id][key].AP <= -1):
                break
            worksheet.write(i+1, 0, user_id)
            worksheet.write(i+1, 1, key)
            worksheet.write(i+1, 2, Pattern_Summary_Dict[user_id][key].length)
            worksheet.write(i+1, 3, Pattern_Summary_Dict[user_id][key].support)
            worksheet.write(i+1, 4, Pattern_Summary_Dict[user_id][key].AR)
            worksheet.write(i+1, 5, Pattern_Summary_Dict[user_id][key].RR)
            worksheet.write(i+1, 6, Pattern_Summary_Dict[user_id][key].AP)
            i = i + 1

def outputPatternToTxt(file_path, pattern_dict):
    with open(file_path, "w", encoding="UTF-8", errors="ignore") as file:
        for j, key in enumerate(pattern_dict.keys()):
            file.write(key + "\t" + str(pattern_dict[key].length) + "\t" + str(pattern_dict[key].support) + "\n")